package com.lht.testDemo;

import org.junit.Test;
import org.springframework.core.DefaultParameterNameDiscoverer;
import sun.misc.Unsafe;

import java.lang.reflect.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Eric
 * @version 1.0
 * @date 2019-09-17
 */
public class UnsafeTest {

    public static class TestAccessibleObject {

        private String name;

        private TestAccessibleObject() {
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

    }


    public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Constructor[] cs = TestAccessibleObject.class.getDeclaredConstructors();
        AccessibleObject.setAccessible(cs, true);
        System.out.println(cs.length);
        for (Constructor c : cs) {
            System.out.println(c.isAccessible());
            TestAccessibleObject t = (TestAccessibleObject) c.newInstance();
            t.setName("hongboliu");
            System.out.println(t.getName());
        }
    }

    @Test
    public void test() throws IllegalAccessException, NoSuchFieldException, InstantiationException {

        Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        Unsafe u = (Unsafe) unsafeField.get(null);

        TestAccessibleObject obj = (TestAccessibleObject) u.allocateInstance(TestAccessibleObject.class);
        obj.setName("1111");
        System.out.println(obj.getName());

    }

    @Test
    public void testClassLoader() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<TestAccessibleObject> t = (Class<TestAccessibleObject>) Thread.currentThread().getContextClassLoader().loadClass("com.lht.testDemo.UnsafeTest.TestAccessibleObject");
        TestAccessibleObject obj = t.newInstance();
        System.out.println(obj);
    }

    @Test
    public void testEmptyList() {
        List list = Collections.emptyList();
        list.add("111");
        list.forEach(e -> System.out.println(e));
    }


    @Test
    public void test11() throws NoSuchMethodException {
        Method method = this.getClass().getMethod("md",Integer.class, String.class);
        DefaultParameterNameDiscoverer discover = new DefaultParameterNameDiscoverer();
        String[] parameterNames = discover.getParameterNames(method);
        System.out.println(Arrays.toString(parameterNames));
    }

    public void md(Integer userId,String addId){
        System.out.println(userId + addId);
    }
}
